package com.example.asa;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 救援资源调度Servlet
 */
@WebServlet("/dispatch")
public class RescueServlet extends HttpServlet {
    // 模拟数据库存储资源信息
    private static Map<String, Resource> resourceMap = new HashMap<>();
    private static List<Task> taskList = new ArrayList<>();

    // 初始化测试数据
    @Override
    public void init() throws ServletException {
        // 初始化救援人员资源
        resourceMap.put("rescuer", new Resource("rescuer", "救援人员", 40, 12));
        resourceMap.put("pump", new Resource("pump", "抽水机", 5, 5));
        resourceMap.put("ambulance", new Resource("ambulance", "救护车", 5, 2));

        // 初始化测试任务
        taskList.add(new Task("R-202507", "XX村小学", "10名抢险人员、2台抽水机", "待分配"));
        taskList.add(new Task("R-202506", "XX街道积水点", "5名人员、1台抽水机", "调度中"));
        taskList.add(new Task("R-202505", "XX医院", "3名医护人员、1辆救护车", "已完成"));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        String action = req.getParameter("action");
        if (action == null) {
            out.println("{\"code\": 400, \"message\": \"缺少action参数\"}");
            return;
        }

        try {
            switch (action) {
                case "getResources":
                    getResources(out);
                    break;
                case "getTasks":
                    getTasks(out);
                    break;
                case "dispatch":
                    dispatchResource(req, out);
                    break;
                default:
                    out.println("{\"code\": 400, \"message\": \"不支持的action: " + action + "\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"code\": 500, \"message\": \"服务器内部错误\"}");
        }
    }

    /**
     * 获取资源列表
     */
    private void getResources(PrintWriter out) {
        StringBuilder json = new StringBuilder();
        json.append("{\"code\": 200, \"data\": [");

        boolean first = true;
        for (Resource resource : resourceMap.values()) {
            if (!first) {
                json.append(",");
            }
            json.append(resource.toJson());
            first = false;
        }

        json.append("]}");
        out.println(json.toString());
    }

    /**
     * 获取任务列表
     */
    private void getTasks(PrintWriter out) {
        StringBuilder json = new StringBuilder();
        json.append("{\"code\": 200, \"data\": [");

        boolean first = true;
        for (Task task : taskList) {
            if (!first) {
                json.append(",");
            }
            json.append(task.toJson());
            first = false;
        }

        json.append("]}");
        out.println(json.toString());
    }

    /**
     * 调度资源
     */
    private void dispatchResource(HttpServletRequest req, PrintWriter out) {
        String taskId = req.getParameter("taskId");
        String resourceType = req.getParameter("resourceType");
        int quantity = Integer.parseInt(req.getParameter("quantity"));

        // 验证参数
        if (taskId == null || resourceType == null || quantity <= 0) {
            out.println("{\"code\": 400, \"message\": \"参数错误\"}");
            return;
        }

        // 查找任务
        Task task = findTaskById(taskId);
        if (task == null) {
            out.println("{\"code\": 404, \"message\": \"任务不存在\"}");
            return;
        }

        // 查找资源
        Resource resource = resourceMap.get(resourceType);
        if (resource == null) {
            out.println("{\"code\": 404, \"message\": \"资源类型不存在\"}");
            return;
        }

        // 检查资源是否充足
        if (resource.getAvailable() < quantity) {
            out.println("{\"code\": 400, \"message\": \"资源不足，可用数量: " + resource.getAvailable() + "\"}");
            return;
        }

        // 更新资源状态
        resource.setAvailable(resource.getAvailable() - quantity);
        resource.setDispatched(resource.getDispatched() + quantity);

        // 更新任务状态
        if ("待分配".equals(task.getStatus())) {
            task.setStatus("调度中");
        }

        // 返回成功响应
        out.println("{\"code\": 200, \"message\": \"调度成功\"}");
    }

    private Task findTaskById(String taskId) {
        for (Task task : taskList) {
            if (task.getTaskId().equals(taskId)) {
                return task;
            }
        }
        return null;
    }
}

/**
 * 资源类
 */
class Resource {
    private String id;
    private String name;
    private int total;
    private int dispatched;

    public Resource(String id, String name, int total, int dispatched) {
        this.id = id;
        this.name = name;
        this.total = total;
        this.dispatched = dispatched;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getTotal() {
        return total;
    }

    public int getDispatched() {
        return dispatched;
    }

    public int getAvailable() {
        return total - dispatched;
    }

    public void setAvailable(int available) {
        this.total = available + dispatched;
    }

    public void setDispatched(int dispatched) {
        this.dispatched = dispatched;
    }

    public String toJson() {
        return String.format("{\"id\": \"%s\", \"name\": \"%s\", \"total\": %d, \"dispatched\": %d, \"available\": %d}",
                id, name, total, dispatched, getAvailable());
    }
}

/**
 * 任务类
 */
class Task {
    private String taskId;
    private String location;
    private String requirement;
    private String status;

    public Task(String taskId, String location, String requirement, String status) {
        this.taskId = taskId;
        this.location = location;
        this.requirement = requirement;
        this.status = status;
    }

    public String getTaskId() {
        return taskId;
    }

    public String getLocation() {
        return location;
    }

    public String getRequirement() {
        return requirement;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String toJson() {
        return String.format("{\"taskId\": \"%s\", \"location\": \"%s\", \"requirement\": \"%s\", \"status\": \"%s\"}",
                taskId, location, requirement, status);
    }
}
